<?php
session_start();
require_once('../model/db.php');
require_once('login.php');

    if (!empty($_POST['_get_function']))
    {
        $email_check="/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/";
        $char_check="/^[A-Za-z\å\ä\ö\Å\Ä\Ö!\?.,:\-_ ]+$/";
        $web_safe_check="/^[A-Za-z0-9\?\&\#.:-_\å\ä\ö\Å\Ä\Ö]+$/";
        $password_check="/^[A-Za-z\å\ä\ö\Å\Ä\Ö.,:-_@#€%&£$\?\§ ]+$/";
        $digit_check="/[0-9]+/";
        $char_digit_check="/^[1-9A-Za-z\å\ä\ö\Å\Ä\Ö ]+$/";
        $name_check="/^[0-9A-Za-z\å\ä\ö\Å\Ä\Ö]{2,40} ?[0-9A-Za-z\å\ä\ö\Å\Ä\Ö]{0,40} ?[0-9A-Za-z\å\ä\ö\Å\Ä\Ö]{0,40}$/";
        $skype_check="/^[0-9A-Za-z\å\ä\ö\Å\Ä\Ö.,:-_@#€%&£$\?\§ ]+$/";
        $birth_date_check="/^[1-2]{1}[09]{1}[0-9]{2}\-[0-1]{1}[0-9]{1}\-[0-3]{1}[0-9]{1}$/";

        foreach ($_POST as $key => $value)
        {
            $validation="false";
            if ($key=="name" || $key=="first_name" || $key=="last_name")
            {
                if (preg_match($name_check,$value)) 					// -[ONLY LETTERS + SPACE]-
                    $validation="true";
            }
            elseif ($key=="email")
            {
                if (preg_match($email_check,$value))					//-[EMAIL CHECK]-
                    $validation="true";
            }
            elseif ($key=="birthdate")
            {
                if (preg_match($birth_date_check,$value))					//-[EMAIL CHECK]-
                    $validation="true";
            }
            elseif ($key=="country" || $key=="city" || $key=="alias")
            {															//-[CHAR CHECK]-
                if (preg_match($char_check,$value))
                    $validation="true";
            }
            elseif ($key=="usernameForm" || $key=="passwordForm")
            {															//-[**********DIPLOMACY LOGIN************ CHECK]-
                if (preg_match($char_check,$value))
                    $validation="true";
            }
            elseif ($key=="diggit" || $key=="game_id") //-[DIGIT CHECK]-
            {
            	if (preg_match($digit_check,$value))
                    $validation="true";
            }
            elseif ($key=="_get_function")	 							//-[FUNCTION CHECK]-
            {
            	if ($value=="add_user" || $value=="login" || $value=="logout" || $value=="new_post" || $value=="file_upload" || $value=="create_game" || $value=="join_game")
                    $validation="true";
            }
            elseif ($key=="skype")                           			//-[CHAR CHECK]-
            {
                if (preg_match($skype_check,$value) || strlen($value)==0)
                    $validation="true";
            }
            elseif ($key=="password")                       			//-[PASSWROD CHECK]-
            {
            	if (preg_match($password_check,$value))
            	{
            		if(isset($_POST['password2']))
            		{
            			if ($value==$_POST['password2'])
            			{
            				$validation="true";
            			}
            		}
            		else
            		{
                    	$validation="true";
            		}
            	}
            }
            elseif ($key=="game_password")
           {															//-[CHAR CHECK]-
                if (preg_match($password_check,$value) || ($value==""))
                    $validation="true";
            }
            elseif ($key=="submit" || 
		            $key=="password2" || 
		            $key=="action" || 
		            $key=="submitLogin"|| 
		            $key=="submitNewGame" || 
		            $key=="start_time"|| 
		            $key=="round_time" || 
		            $key=="start_date" || 
		            $key=="map" )       			//-[NO VALUE SET]- (inget som skrivs in direkt i databasen)
            {
               	$validation="true";
            }
            else                    									//-[NO VALIDATION]-
            {
            	$validation="false";
            }
            $values[$key] = array("value" => trim($value), "validated" => $validation);
        }

        $error_string="";

    	foreach ($values as $key => $value) //Går igenom arrayen med alla poster
		{
			if ($value['validated']=="false")
				$error_string.="Felaktig inmatning: ". $key . ": ". $value['value'] . " " . $value['validated'] ."<br />";
		}

		if ($error_string) {
			echo $error_string;
			die;
		}

        if ($values['_get_function']['validated']=="true")
             $function=$values['_get_function']['value'];

        if (isset($function))
            call_user_func($values['_get_function']['value'],$values);
    }


    function file_upload($values)
    {
    if ((($_FILES["file"]["type"] == "image/gif")
		|| ($_FILES["file"]["type"] == "image/jpeg")
		|| ($_FILES["file"]["type"] == "image/png")
		|| ($_FILES["file"]["type"] == "image/jpg"))
		&& ($_FILES["file"]["size"] < 2000000)) {
			
		$user_id=$_SESSION['user_id'];
		if ($_FILES["file"]["error"] > 0) {
		  	echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
		} else {
//		    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
//		    echo "Type: " . $_FILES["file"]["type"] . "<br />";
//		    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
//		    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
	
			$fileending = strstr($_FILES["file"]["name"],".",false);
			$_FILES["file"]["name"]=$user_id.$fileending;
		    move_uploaded_file($_FILES["file"]["tmp_name"],
		    "../upload/" . $_FILES["file"]["name"]);
		    update_db(array('avatar' => "upload/".$_FILES["file"]["name"]), 'users', "id = $user_id");
		 
	       	header('Location: ../index.php?p=uploadavatar');
		      
		    }
		} else {
//		    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
//		    echo "Type: " . $_FILES["file"]["type"] . "<br />";
//		    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
//		    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
//			
			echo "Invalid file";
		}
    }

    function add_user($values)
    {
        $alias=$values['alias']['value'];
        $first_name=$values['first_name']['value'];
        $last_name=$values['last_name']['value'];
        $email=$values['email']['value'];
        $skype=$values['skype']['value'];
        $country=$values['country']['value'];
        $city=$values['city']['value'];
        $birth_date=$values['birthdate']['value'];
        $password=$values['password']['value'];

        $userinfo = select_from_db(array('alias', 'email'),array('users'),array("alias='$alias'")); 
			
        if (isset($userinfo[0]['alias'])) {
	       	header('Location: ../index.php?p=1');//Användarnamnet upptaget.
            
        } else {
	        $user_id = insert_to_db(array( 'alias' => $alias,'first_name' => $first_name,'last_name' => $last_name, 'email' => $email, 'password' => $password, 'skype' => $skype, 'city' => $city, 'country' => $country, 'birth_date' => $birth_date), 'users');
	        $_SESSION['user_id'] = $user_id; //Sätter anändarid i en session
            $_SESSION['user_name'] = $alias;	       	
	        header('Location: ../index.php?p=startpage');//Inloggad användare
        }
    }

    function create_game($values)
    {	
        $map=$values['map']['value'];
        $name=$values['name']['value'];
        $start_time=$values['start_time']['value'];
        $round_time=$values['round_time']['value'];
        $user_id=$_SESSION['user_id'];
        $password=$values['game_password']['value'];
        
        $country=$values['country']['value'];
       	$alias = select_from_db(array('alias'),array('users'),array("id='$user_id'")); 
        $alias = $alias[0]['alias'];
		$timeleft = "00" . $round_time . "00";

        $game_id = insert_to_db(array( 'name' => $name,'start_time' => $start_time,'round_time' => $round_time, 'owner_id' => $user_id, 'map' => $map, 'password' => $password, 'timeleft' => $timeleft), 'games');
		$chat_room_id = insert_to_db(array('owner_id' => $user_id,'game_id' => $game_id, 'name' => $name), 'chat_rooms');
		insert_to_db(array('chat_room_id' => $chat_room_id,'user_id' => $user_id), 'chat_rooms__got__users');		
		insert_to_db(array('game_id' => $game_id,'user_id' => $user_id,'land' => $country), 'users__got__games');
        insert_to_db(array('chat_room_id' => $chat_room_id,'user_id' => $user_id,'message' => "*** $alias has entered the room ***"), 'chat_messages');
		update_db(array($country => $user_id), 'games', "id = $game_id");
       	header("Location: ../index.php?p=game_lobby&g=$game_id");
    }

    function join_game($values)
    {
        $game_id=$values['game_id']['value'];
        
        $password = isset($values['game_password']['value'])?$values['game_password']['value']:"";
        
        $country=$values['country']['value'];
        $user_id=$_SESSION['user_id'];
       	$password_check = select_from_db(array('password'),array('games'),array("id='$game_id'")); 
	        
        $passchk = $password_check[0]['password'];
        if ($passchk==$password || empty($passchk)) {   
       		$alias = select_from_db(array('alias'),array('users'),array("id='$user_id'")); 
        	$alias = $alias[0]['alias'];
			update_db(array($country => $user_id), 'games', "id = $game_id");
	        insert_to_db(array('game_id' => $game_id,'user_id' => $user_id,'land' => $country), 'users__got__games');
	       	$chat_room_id = select_from_db(array('id'),array('chat_rooms'),array("game_id='$game_id'")); 
			$chat_room_id = $chat_room_id[0]['id'];
	        insert_to_db(array('chat_room_id' => $chat_room_id,'user_id' => $user_id,'message' => "*** $alias has entered the room ***"), 'chat_messages');
	        insert_to_db(array('chat_room_id' => $chat_room_id,'user_id' => $user_id), 'chat_rooms__got__users');
	       	header("Location: ../index.php?p=game_lobby&g=$game_id");	
	      } else {
	       	header("Location: ../index.php?p=games");
	      }
    }
    
    function login($values)
    {
    $alias=$values['usernameForm']['value'];
    $password=$values['passwordForm']['value'];
        if($alias && $password)
        {
            $userinfo = select_from_db(array('password', 'id'),array('users'),array("alias='$alias'")); //hämtar hem användaruppgifter från angiven email

            if ($password==$userinfo[0]['password']) { //Kontrollerar om lösenordet stämmer
            	$date = date("Y-m-d H:i:s");
            	$user_id = $userinfo[0]['id'];
            	
            	$visits = select_from_db(array('visits'), array('users'), array("id=$user_id"));
            	$visits=$visits[0]['visits'];
            	
				update_db(array('visits' => $visits+1, 'last_visit' => $date), 'users', "id = $user_id");
            	
            	
            	
                $_SESSION['user_id'] = $userinfo[0]['id']; //Sätter anändarid i en session
                $_SESSION['user_name'] = $alias;
                header('Location: ../?p=startpage');
            } else {
                header('Location: ../index.php?msg=1');//Användarnamnet och lösenordet stämmer inte överens
            }

        }
        else
        {
            header('Location: ../index.php?msg=2');//Inget användarnamn eller lösenord angvet
        }

    }

    function logout()
    {
        $_SESSION = array();
        header('Location: ../index.php?msg=3'); //Du är nu utloggad
    }
